package DynamicArray;

import java.util.Iterator;
import java.util.function.Consumer;

public class DynamicArray implements Iterable<Integer>{

    private int size = 0;
    private int capacity = 8 ;
    private int[] array ={};

    //插入
    public void addLast(int element){
     //   array[size] = element;
        // size++;
        add(size,element);
    }
    public void add(int index, int element){
        checkAndGrow();
        if(index >= 0 && index < size) {
            System.arraycopy(array, index, array, index + 1, size - index);//拷贝数组
        }
        array[index] = element;
        size++;
    }
    //扩容
    private void checkAndGrow() {
        if(size == 0){
            array = new int [capacity];
        }
       else if(size == capacity){
            capacity += capacity >>>1;
            int[] newArray = new int[capacity];
            System.arraycopy(array,0,newArray,0,size);
            array = newArray;
        }
    }

    public int getIndex(int index){
        return array[index];
    }
    //遍历
    public void foreach(Consumer<Integer> consumer){
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }
    //删除
    public int remove(int index){
        int removed = array[index];
        if(index < size-1){
            System.arraycopy(array,index+1,array,index,size-index-1);
        }
        size--;
        return removed;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            private int index = 0;
            @Override
            public boolean hasNext() {
                return index<size;
            }

            @Override
            public Integer next() {
                return array[index++];
            }
        };
    }
}

